﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using GioHangViet.Areas.Admin.Models;
using GioHangViet.Models;

namespace GioHangViet.Areas.Admin.Controllers
{
    public class UsersController : Controller
    {
        private readonly GoLungTungModel _db = new GoLungTungModel();
        /// <summary>
        /// List all user.
        /// </summary>
        /// <param name="id">page id</param>
        /// <returns></returns>
        public ViewResult Index(int id)
        {
            var currentPage = id;
            if (id < 0)
            {
                currentPage = 1;
            }
            ViewBag.CurrentPage = currentPage;
            ViewBag.countRecord = _db.Users != null ? _db.Users.Count() : 0;
            var pageSize = 10D;
            ViewBag.PageSize = Double.TryParse(Resources.Constant.PageSize, out pageSize) ? pageSize : pageSize;
            ViewBag.PageSize = Convert.ToDouble(Resources.Constant.PageSize);
            var model = _db.Users.OrderBy(item => item.UserName).Skip((currentPage - 1) * (int)pageSize).Take((int)pageSize);
            return View(model);
        }

        //
        // GET: /Admin/Users/Details/5

        public ViewResult Details(string id)
        {
            User user = _db.Users.Find(id);
            return View(user);
        }

        //
        // GET: /Admin/Users/Create

        public ActionResult Create()
        {

            ViewBag.ImagesAvata = GetAllAvata();
            ViewBag.Provice = new SelectList(_db.Provices.OrderBy(item => item.Name).ToList(), "Id", "Name");
            return View();
        }

        //
        // POST: /Admin/Users/Create

        [HttpPost]
        public ActionResult Create(User user, FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files.Count > 0)
                {
                    if (string.IsNullOrWhiteSpace(Request.Files[0].FileName))
                    {
                        var file = Request.Files[0];
                        if (file != null)
                        {
                            var name = ProcessAlias.ConvertToUnSign(file.FileName);
                            //
                            // Kiểm tra nếu tên file đã tồn tại thì thêm chuỗi gồm millisecond, second, minute, hour, day, month, year vào trước
                            // file name để loại bỏ sự trùng tên.
                            //
                            if (System.IO.File.Exists(Server.MapPath("~/Content/images/Avata/") + name))
                            {
                                name = DateTime.Now.Millisecond + DateTime.Now.Second.ToString(CultureInfo.InvariantCulture) +
                                       DateTime.Now.Minute + DateTime.Now.Hour + DateTime.Now.Day + DateTime.Now.Month +
                                       DateTime.Now.Year + name;
                            }
                            //
                            // Lưu file trên server.
                            //
                            file.SaveAs(Server.MapPath("~/Content/images/Avata/") + name);
                            user.Avatar = name;
                        }
                    }
                }
                else
                {
                    user.Avatar = collection["ImageAvata"].Substring(collection["ImageAvata"].LastIndexOf('/') + 1);
                }

                //
                // Get provice name for user
                //
                int proviceId;
                if (int.TryParse(collection["Provice"], out proviceId))
                {
                    user.Provice = _db.Provices.Find(proviceId).Name;
                }

                //
                // Get ward for user
                //
                int district;
                if (int.TryParse(collection["District"], out district))
                {
                    user.District = _db.Wards.Find(district).Name;
                }

                //
                // Get address for user
                //
                user.Address = user.Ward + " " + user.District + " " + user.Provice;
                user.Password = ProcessAlias.Encrypt(user.Password);
                user.SecretKey = ProcessAlias.Encrypt(ProcessAlias.GetPassword());
                user.CreateDate = DateTime.Now;
                user.LastestLogon = DateTime.Now;
                user.IntroCount = 0; 
                _db.Users.Add(user);
                _db.SaveChanges();
                return RedirectToAction("Index", new{ id = 1});
            }

            ViewBag.ImagesAvata = GetAllAvata();
            return View(user);
        }

        //
        // GET: /Admin/Users/Edit/5

        public ActionResult Edit(string id)
        {
            User user = _db.Users.Find(id);
            return View(user);
        }

        //
        // POST: /Admin/Users/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                _db.Entry(user).State = EntityState.Modified;
                _db.SaveChanges();
                return RedirectToAction("Index", new{ id = 1});
            }
            return View(user);
        }

        //
        // GET: /Admin/Users/Delete/5

        public ActionResult Delete(string id)
        {
            User user = _db.Users.Find(id);
            return View(user);
        }

        //
        // POST: /Admin/Users/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            User user = _db.Users.Find(id);
            _db.Users.Remove(user);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        /// <summary>
        /// Hàm thay đổi status
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult LockAccount(string id)
        {
            return Json("");
        }

        public SelectList GetAllAvata()
        {
            var files = Directory.GetFiles(Server.MapPath(@"~/Content/images/Avata/Default/")).Where(item => item.Substring(item.LastIndexOf('.')).ToLower() == ".png" || item.Substring(item.LastIndexOf('.')).ToLower() == ".jpg" || item.Substring(item.LastIndexOf('.')).ToLower() == ".gif").Select(item => new { source = "/Content/images/Avata/Default/" + item.Substring(item.LastIndexOf('\\') + 1), Name = item.Substring(item.LastIndexOf('\\') + 1) }).ToList();
            return new SelectList(files, "Source", "Name");
        }

        public JsonResult GetDistrict(int id)
        {
            var listProduct = (from p in _db.Wards where p.ProviceId == id orderby p.Name select new { p.Id, p.Name }).ToList();

            return Json(new { ListProduct = listProduct },
                        JsonRequestBehavior.AllowGet);
        }

        public JsonResult CheckExsistUserName()
        {
            return Json(string.IsNullOrWhiteSpace(Request.QueryString["username"]) ? new { Enable = false } : new { Enable = _db.Users.Any(item => !item.Email.Equals(Request.QueryString["username"])) }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult CheckExsistEmail()
        {
            return Json(string.IsNullOrWhiteSpace(Request.QueryString["email"]) ? new { Enable = false } : new {Enable = _db.Users.Any(item => item.Email.Equals(Request.QueryString["email"]))}, JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }
    }
}